//
//  GesturePasswordController.m
//  GesturePassword
//
//  Created by hb on 14-8-23.
//  Copyright (c) 2014年 黑と白の印记. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "GesturePasswordController.h"
#import "UIUtil.h"
#import <Security/Security.h>
#import <CoreFoundation/CoreFoundation.h>


#import "KeychainItemWrapper/KeychainItemWrapper.h"
//#import "CAccountMgr.h"
//#import "CAccountModel.h"
#import "MicroDef.h"
#import "LoginViewController.h"
#import "CUserSettingMgr.h"
#import "CUserSettingModel.h"
#import "CFolderMgr.h"
#import "CXmppMgr.h"
#import "CXmppRequestMgr.h"



#define KMaxErrorTimes 3

@interface GesturePasswordController ()
{
    NSInteger _errorTimes;
}

@property (nonatomic,strong) GesturePasswordView * gesturePasswordView;
@property (nonatomic, strong) CUserSettingMgr *setMgr;
//@property (nonatomic, strong) CAccountMgr *accMgr;
@property (nonatomic, strong) CUserSettingModel *setting;
@property (nonatomic, strong) CAccountModel *account;

@end

@implementation GesturePasswordController {
    NSString * previousString;
    NSString * password;
}

@synthesize gesturePasswordView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _errorTimes = 0;
    // Do any additional setup after loading the view.
    previousString = [NSString string];
//    KeychainItemWrapper * keychin = [[KeychainItemWrapper alloc]initWithIdentifier:@"Gesture" accessGroup:nil];
//    password = [keychin objectForKey:(__bridge id)kSecValueData];
    password = [USER_DEFAULT objectForKey:GUESTUREPASSWORD];
////    if ([password isEqualToString:@""])
//    if(0)
////    if(1)
//    {
//        
//        [self reset];
//    }
//    else {
        [self verify];
//    }
    
    
    self.account = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];

//    self.view.backgroundColor = [UIColor redColor];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 验证手势密码
- (void)verify{
    gesturePasswordView = [[GesturePasswordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [gesturePasswordView.tentacleView setRerificationDelegate:self];
    [gesturePasswordView.tentacleView setStyle:1];
    [gesturePasswordView setGesturePasswordDelegate:self];
    [self.view addSubview:gesturePasswordView];
    gesturePasswordView.guesView.hidden = YES;
    gesturePasswordView.imgView.hidden = NO;
    gesturePasswordView.headerImageView.hidden = NO;
    [gesturePasswordView.state setText:@"请输入手势密码"];
//    gesturePasswordView.backgroundColor = [UIColor clearColor];
    [gesturePasswordView.changeButton setHidden:YES];
    [gesturePasswordView.forgetButton setHidden:NO];
    [gesturePasswordView.reLoginButton setHidden:YES];
}

#pragma mark - 重置手势密码
- (void)reset{
    gesturePasswordView = [[GesturePasswordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [gesturePasswordView.tentacleView setResetDelegate:self];
    [gesturePasswordView.tentacleView setStyle:2];
//    [gesturePasswordView.imgView setHidden:YES];
    [gesturePasswordView.forgetButton setHidden:NO];
    [gesturePasswordView.changeButton setHidden:NO];
    [self.view addSubview:gesturePasswordView];
}

#pragma mark - 判断是否已存在手势密码
- (BOOL)exist{
    KeychainItemWrapper * keychin = [[KeychainItemWrapper alloc]initWithIdentifier:@"Gesture" accessGroup:nil];
    password = [keychin objectForKey:(__bridge id)kSecValueData];
    if ([password isEqualToString:@""])return NO;
    return YES;
}

#pragma mark - 清空记录
- (void)clear{
    KeychainItemWrapper * keychin = [[KeychainItemWrapper alloc]initWithIdentifier:@"Gesture" accessGroup:nil];
    [keychin resetKeychainItem];
}

#pragma mark - 改变手势密码
- (void)change{
}

#pragma mark - 忘记手势密码
- (void)forget{
    
    [USER_DEFAULT setBool:YES forKey:ISFORCEQUIT];
    [USER_DEFAULT setBool:NO forKey:is_GuseturePassword];
    [USER_DEFAULT setObject:@"" forKey:GUESTUREPASSWORD];
    [USER_DEFAULT setBool:YES forKey:is_ForgetGuesturePassword];
    [USER_DEFAULT synchronize];
//    [[CXmppMgr shareInstance] goOffline];
    [[CXmppMgr shareInstance] disconnect];
    [[CXmppRequestMgr shareInstance] quitLoad];
    
    //用户退出到登录界面必须清空#pragma mark 用户退出登录以后必须清空 [CFolderMgr shareInstance].recentlyAcc = nil；
    [CFolderMgr shareInstance].recentlyAcc = nil;

    UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//    for (UIViewController *vc in rotNav.childViewControllers) {
//        if ([vc isKindOfClass:[LeveyTabBarController class]]) {
//            LeveyTabBarController *lev = (LeveyTabBarController *)vc;
//            for (CHSNavigationController *naVc  in lev.viewControllers) {
//                for (UIViewController *vc in naVc.childViewControllers) {
//                    [vc.navigationController popToRootViewControllerAnimated:NO];
//                }
//            }
//            
//        }
//    }
    for (UIViewController *vc in rotNav.childViewControllers) {
        if ([vc isKindOfClass:[LoginViewController class]]) {
            LoginViewController *login = (LoginViewController *)vc;
            [login setverifyStatus:NO];
            login.errTimes = 0;
             login.isUseverifyCode = NO;
            [login setErrStatus:NO errorMsg:nil];
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    [rotNav popToRootViewControllerAnimated:NO];

}

- (BOOL)verification:(NSString *)result{
    
    if(M_ISSTRNULL(result))
    {
        return NO;
    }
    
    if ([result isEqualToString:password]) {
//        [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
        [gesturePasswordView.state setText:@"输入正确"];
        //[self presentViewController:(UIViewController) animated:YES completion:nil];
//        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
        return YES;
    }
    _errorTimes++;
    if (_errorTimes < KMaxErrorTimes) {
        [gesturePasswordView.state setTextColor:RGBCOLOR(0xf4, 0x62, 0x0b)];
        //    [gesturePasswordView.state setText:@"手势密码错误"];
        //    [gesturePasswordView.state setText:@"密码错误, 还有2次输入机会"];
        [gesturePasswordView.state setText:[NSString stringWithFormat:@"密码错误, 还有%zd次输入机会", KMaxErrorTimes - _errorTimes ]];
        [gesturePasswordView.errorMsg setHidden:NO];
        return NO;
    } else {
        [gesturePasswordView.state setText:[NSString stringWithFormat:@"您输入错误密码的次数过多" ]];
        [USER_DEFAULT setBool:NO forKey:is_GuseturePassword];
        [USER_DEFAULT setBool:YES forKey:is_ForgetGuesturePassword];
        [USER_DEFAULT setObject:@"" forKey:GUESTUREPASSWORD];
        [USER_DEFAULT setBool:YES forKey:ISFORCEQUIT];
        [USER_DEFAULT synchronize];
//        [[CXmppMgr shareInstance] goOffline];
        [[CXmppMgr shareInstance] disconnect];
        [[CXmppRequestMgr shareInstance] quitLoad];
        //用户退出到登录界面必须清空#pragma mark 用户退出登录以后必须清空 [CFolderMgr shareInstance].recentlyAcc = nil；
        [CFolderMgr shareInstance].recentlyAcc = nil;

        UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        //    for (UIViewController *vc in rotNav.childViewControllers) {
        //        if ([vc isKindOfClass:[LeveyTabBarController class]]) {
        //            LeveyTabBarController *lev = (LeveyTabBarController *)vc;
        //            for (CHSNavigationController *naVc  in lev.viewControllers) {
        //                for (UIViewController *vc in naVc.childViewControllers) {
        //                    [vc.navigationController popToRootViewControllerAnimated:NO];
        //                }
        //            }
        //
        //        }
        //    }
        for (UIViewController *vc in rotNav.childViewControllers) {
            if ([vc isKindOfClass:[LoginViewController class]]) {
                LoginViewController *login = (LoginViewController *)vc;
                [login setverifyStatus:NO];
                login.errTimes = 0;
                 login.isUseverifyCode = NO;
                [login setErrStatus:NO errorMsg:nil];
            }
        }
        [rotNav popToRootViewControllerAnimated:NO];
        [self dismissViewControllerAnimated:YES completion:nil];
        return NO;
    }
    return NO;
}

- (BOOL)resetPassword:(NSString *)result{
    if ([previousString isEqualToString:@""]) {
        previousString=result;
        [gesturePasswordView.tentacleView enterArgin];
//        [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
        [gesturePasswordView.state setText:@"请验证输入密码"];
        return YES;
    }
    else {
        if ([result isEqualToString:previousString]) {
            KeychainItemWrapper * keychin = [[KeychainItemWrapper alloc]initWithIdentifier:@"Gesture" accessGroup:nil];
            [keychin setObject:@"<帐号>" forKey:(__bridge id)kSecAttrAccount];
            [keychin setObject:result forKey:(__bridge id)kSecValueData];
            //[self presentViewController:(UIViewController) animated:YES completion:nil];
//            [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
            [gesturePasswordView.state setText:@"已保存手势密码"];
            return YES;
        }
        else{
            previousString =@"";
//            [gesturePasswordView.state setTextColor:[UIColor redColor]];
            [gesturePasswordView.state setText:@"您输入的密码与上次不一致"];
            [gesturePasswordView.errorMsg setHidden:NO];
            return NO;
        }
    }
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
